import axios from 'axios'
import { Message, Loading } from 'element-ui'
import router from '@/router'
// import store from '../store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 2000000 // request timeout
})
let loading

// loading开始
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0,0,0,0.7)'
  })
}
// loading结束
function endLoading() {
  loading.close()
}
let loadingCount = 0
// 这些URL 不需要loading
const url = ['/bomTree/saveBomTree', '/tJxMessageStore/queryUserMessageNoRead',
  '/tJxMessageStore/getSubscrMessage', '/log/checkLoginToken', '/common/updateBillLock',
  '/reportpoo/queryRealTimeDataBalance', '/tBaseDataDictionary/queryViewItem', '/tJxMessageStore/queryUserMessageReadAndNoReview']
export function startLoadingAddCount(ev) {
  if (loadingCount === 0 && !url.includes(ev)) {
    startLoading()
  }
  loadingCount++
}

export function endLoadingSubCount() {
  loadingCount > 0 && loadingCount--
  if (loadingCount === 0) {
    endLoading()
  }
}
const publicPath = location.pathname
// request interceptor
service.interceptors.request.use(
  config => {
    startLoadingAddCount(config.url)
    /* 待给所有接口携带上用户fuserId 组织forgid*/
    const fuserId = window.sessionStorage.getItem('fuserId')
    const forgid = window.sessionStorage.getItem('forgid')
    const flanguage = localStorage.getItem('lang') || 'zh'
    // 忽略 fuserId 的接口
    const urlArr = ['/tSalPositionUser/addPositionUser', '/tJxSearch/deleteTJxSearch', '/tJxMessageUser/delMessageUser',
      '/tJxMessageUser/insertMessageUser', '/tSecUser/insertTSecUser', '/tSecUser/queryUserDetails']
    // 判断是否是忽略的接口
    const inde = urlArr.includes(config.url)
    if (['post', 'put', 'delete'].includes(config.method)) {
      if (!inde) {
        config.data['fuserId'] = fuserId
        config.data['forgid'] = forgid
        config.data['flanguage'] = flanguage
      }
    }
    // 杰希、摩洛哥、内销
    if (publicPath.indexOf('jc-web') !== -1) { // 惠州杰希
      config.url = '/jc' + config.url
    } else if (publicPath.indexOf('mlg-web') !== -1) { // 摩洛哥
      config.url = '/mlg' + config.url
    } else if (publicPath.indexOf('nx-web') !== -1) { // 惠州杰希内销
      config.url = '/nx' + config.url
    } else if (publicPath.indexOf('jnk-web') !== -1) { // jnk
      config.url = '/jnk' + config.url
    }
    return config
  },
  error => {
    endLoadingSubCount()
    // do something with request error
    return Promise.reject(error)
  }
)
// sessionStorage.removeItem('fuserId')
// this.$store.dispatch('logout')
// response interceptor
service.interceptors.response.use(
  response => {
    endLoadingSubCount()
    const res = response.data
    if (res.code === 0) {
      return Promise.resolve(res)
    } else if (res.code === 2) {
      return Promise.resolve(res)
    } else if (res.code === 400) {
      // sessionStorage.removeItem('fuserId')
      // sessionStorage.removeItem('loginToken')
      router.replace({
        name: 'login'
      })
    } else if (res.code === 1 || res.code === -1) {
      return Promise.resolve(res)
    } else {
      return Message({
        message: res.message || '网络异常，请重新尝试',
        type: 'warning',
        showClose: true,
        duration: 2 * 1000
      })
    }
  },
  error => {
    endLoadingSubCount()
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          // sessionStorage.removeItem('fuserId')
          // sessionStorage.removeItem('loginToken')
          // router.replace({
          //   name: 'login'
          // })
          Message({
            message: '网络连接错误，请重新尝试！',
            type: 'error',
            showClose: true,
            duration: 2 * 1000
          })
          break
        case 404:
          Message({
            message: '网络请求不存在！',
            type: 'error',
            showClose: true,
            duration: 2 * 1000
          })
          break
        case 502:
          Message({
            message: '当前服务器不稳定，请稍后尝试！',
            type: 'error',
            showClose: true,
            duration: 2 * 1000
          })
          break
        default:
          Message({
            message: error.response.data.message,
            type: 'error',
            showClose: true,
            duration: 2 * 1000
          })
      }
    }
    return Promise.reject(error.response)
  }
)

export default service
